package com.koushikdutta.async.future;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

/**
 * Created by koush on 12/25/13.
 */
public class HandlerFuture<T> extends SimpleFuture<T> {
    EventHandler handler;

    public HandlerFuture() {
        EventRunner looper = EventRunner.current();
        if (looper == null)
            looper = EventRunner.getMainEventRunner();
        handler = new EventHandler(looper);
    }

    @Override
    public void setCallback(final FutureCallback<T> callback) {
        FutureCallback<T> wrapped = new FutureCallback<T>() {
            @Override
            public void onCompleted(final Exception e, final T result) {
                if (EventRunner.current() == handler.getEventRunner()) {
                    callback.onCompleted(e, result);
                    return;
                }

                handler.postTask(new Runnable() {
                    @Override
                    public void run() {
                        onCompleted(e, result);
                    }
                });
            }
        };
        super.setCallback(wrapped);
    }
}
